//
//  PlayerViewController.m
//  SuperNews
//
//  Created by dllo on 16/1/14.
//  Copyright © 2016年 qiang. All rights reserved.
//

#import "PlayerViewController.h"
#import "STKAudioPlayer.h"
#import "ListenListDetailTableViewCell.h"
#import "RadioModel.h"
#import "MusicModel.h"

@interface PlayerViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableV;
@property (nonatomic, strong) NSMutableArray *musicArr;

@property (nonatomic, strong) UIButton *playB;

@property (nonatomic, strong) UIButton *stopB;

@property (nonatomic, strong) UISlider *volS;
@property (nonatomic, strong) UISlider *timeS;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) CABasicAnimation *basicA1;

@property (nonatomic, strong) UILabel *beginLabel;
@property (nonatomic, strong) UILabel *endLabel;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, assign) BOOL ret;

@property (nonatomic, copy) NSString *oldId;

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *endTimeLabel;

@end

@implementation PlayerViewController

+ (instancetype)sharePlayerViewController
{
    static PlayerViewController *playerVC = nil;
    if (nil == playerVC) {
        playerVC = [[PlayerViewController alloc] init];
        playerVC.number = 0;
        playerVC.index = 0;
        playerVC.ret = NO;
        playerVC.musicArr = [NSMutableArray array];
    }
    return playerVC;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"noplaying" object:nil];
    if (self.cid != [PlayerViewController sharePlayerViewController].oldId) {
        self.number = 0;
        self.index = 0;
        self.ret = NO;
        self.musicArr = [NSMutableArray array];
        [self.player stop];
//        [self createViews];
        [self getData];
        [self getMusicData];
        [self.tableV reloadData];
    }
    if (self.playB.selected) {
        self.basicA1 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        self.basicA1.fromValue = @(0);
        self.basicA1.toValue = @(2 * M_PI);
        self.basicA1.duration = 15.0;
        self.basicA1.repeatCount = NSIntegerMax;
        [self.imageV1.layer addAnimation:self.basicA1 forKey:@"bbb"];
    }
    [self.tableV reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createViews];
    [self getMusicData];
    [self getData];
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (void)createViews
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 230, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 230) style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    if (0 == self.index) {
        self.oldId = self.cid;
    }
    [self.tableV registerClass:[ListenListDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    }];
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 250)];
    imageV.image = [UIImage imageNamed:@"audionews_play_bg"];
    [self.view addSubview:imageV];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 20, 40, 40);
    [backBtn setImage:[UIImage imageNamed:@"bobo_top_navigation_back_highlighted"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 40)];
    self.label.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2.0, 40);
    self.label.textColor = [UIColor whiteColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.label];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 220, 60, 30)];
    self.timeLabel.text = @"00:00";
    self.timeLabel.font = [UIFont systemFontOfSize:11.0];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.timeLabel];
    
    self.endTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 80, 220, 60, 30)];
    self.endTimeLabel.text = @"--:--";
    self.endTimeLabel.textAlignment = NSTextAlignmentRight;
    self.endTimeLabel.font = [UIFont systemFontOfSize:11.0];
    self.endTimeLabel.textColor = [UIColor whiteColor];
    self.endTimeLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.endTimeLabel];
    
    STKAudioPlayerOptions playerOptions = {YES, YES, {50, 100, 200, 400, 800, 1600, 2600, 16000}};
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:playerOptions];
    self.player.volume = 0.5;
    
    self.imageV1 = [[UIImageView alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 130) / 2.0, 70, 130, 130)];
    self.imageV1.layer.masksToBounds = YES;
    self.imageV1.userInteractionEnabled = YES;
    self.imageV1.layer.cornerRadius = 65;
    [self.view addSubview:self.imageV1];
    
    self.playB = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playB.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 130) / 2.0 + 40, 70 + 40, 50, 50);
    [self.playB setImage:[UIImage imageNamed:@"audionews_play_button"] forState:UIControlStateNormal];
    [self.playB setImage:[UIImage imageNamed:@"audionews_pause_button"] forState:UIControlStateSelected];
    [self.playB addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playB];
    
    self.timeS = [[UISlider alloc] initWithFrame:CGRectMake(20, 210, [UIScreen mainScreen].bounds.size.width - 40, 10)];
    //    self.timeS.maximumValue = 169;
    self.timeS.minimumTrackTintColor = [UIColor whiteColor];
    [self.timeS setThumbImage:[UIImage imageNamed:@"audionews_slider_dot"] forState:UIControlStateNormal];
    [self.view addSubview:self.timeS];
    [self.timeS addTarget:self action:@selector(timeAction) forControlEvents:UIControlEventValueChanged];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 40) / 2.0 + 120, 110, 40, 40);
    [btn setImage:[UIImage imageNamed:@"audionews_next_button"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 40) / 2.0 - 120, 110, 40, 40);
    [btn1 setImage:[UIImage imageNamed:@"audionews_previous_button"] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(btn1Action) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    [self playAction];
    
}

- (void)backAction
{
    NSString *command = nil;
    if (YES == self.playB.selected) {
        command = @"playing";
    } else {
        command = @"noplaying";
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:command object:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)timeAction
{
    [self.player seekToTime:self.timeS.value];
}

- (void)playAction
{
    if (STKAudioPlayerStatePlaying == self.player.state) {
        [self.player pause];
        self.playB.selected = NO;
        [[NSUserDefaults standardUserDefaults] setBool:self.playB.selected forKey:@"isplayer"];
        [self.imageV1.layer removeAnimationForKey:@"bbb"];
    } else if (STKAudioPlayerStatePaused == self.player.state) {
        [self.player resume];
        self.playB.selected = YES;
        self.basicA1 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        self.basicA1.fromValue = @(0);
        self.basicA1.toValue = @(2 * M_PI);
        self.basicA1.duration = 15.0;
        self.basicA1.repeatCount = NSIntegerMax;
        [self.imageV1.layer addAnimation:self.basicA1 forKey:@"bbb"];
    } else {
        [self.player play:[[self.listenArr objectAtIndex:0] url_mp4]];
        self.label.text = [[self.listenArr objectAtIndex:0] alt];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(trackAction) userInfo:nil repeats:YES];
        self.playB.selected = YES;
        [[NSUserDefaults standardUserDefaults] setBool:self.playB.selected forKey:@"isplayer"];
        self.basicA1 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        self.basicA1.fromValue = @(0);
        self.basicA1.toValue = @(2 * M_PI);
        self.basicA1.duration = 15.0;
        self.basicA1.repeatCount = NSIntegerMax;
        [self.imageV1.layer addAnimation:self.basicA1 forKey:@"bbb"];
    }
}

- (void)trackAction
{
    if (STKAudioPlayerStateStopped == self.player.state && 0 < self.timeS.value) {
        self.index++;
        [self.player stop];
        self.playB.selected = NO;
        [self.timer invalidate];
        self.timeS.value = 0;
        [self tableView:self.tableV didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0]];
    }
    self.timeS.maximumValue = (NSInteger)self.player.duration;
    self.timeS.value = self.player.progress;
    self.timeLabel.text = [self changeTimer:self.player.progress];
    self.endTimeLabel.text = [self changeEndTimer:(self.player.duration - self.player.progress)];
    
}

- (void)btnAction
{
    self.index++;
    if (self.index == self.musicArr.count) {
        self.index--;
    } else {
        [self.player stop];
        self.playB.selected = NO;
        [self.timer invalidate];
        self.timeS.value = 0;
        [self tableView:self.tableV didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0]];
    }
    [self.tableV reloadData];
}

- (void)btn1Action
{
    if (0 == self.index) {
        self.index = 0;
    } else {
        self.index--;
    }
    [self.player stop];
    self.playB.selected = NO;
    [self.timer invalidate];
    self.timeS.value = 0;
    [self tableView:self.tableV didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0]];
    [self.tableV reloadData];
}

- (void)stopAction
{
    [self.player stop];
    self.playB.selected = NO;
    [self.timer invalidate];
    self.timeS.value = 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.musicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RadioModel *radio = [self.musicArr objectAtIndex:indexPath.row];
    ListenListDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.titleLabel.text = radio.title;
    if (self.index == indexPath.row) {
        cell.titleLabel.textColor = [UIColor redColor];
        [cell.imageV startAnimating];
    } else {
        cell.titleLabel.textColor = [UIColor blackColor];
        [cell.imageV stopAnimating];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self stopAction];
    if (0 == self.musicArr.count) {
    } else {
    RadioModel *radio = [self.musicArr objectAtIndex:indexPath.row];
    if (nil == radio) {
    } else {
        self.docid = radio.docid;
        self.index = indexPath.row;
        [self getMusicData];
        [self.tableV reloadData];
    }
    }
}

- (void)getData
{
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/%ld-20.html", self.cid, self.number];
    [AFNetTool getNetWithURL:str body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSMutableArray *arr = [responseObject objectForKey:self.cid];
        [self.musicArr addObjectsFromArray: [RadioModel baseModelWithArr:arr]];
        [self.tableV reloadData];
        [self.tableV.mj_footer endRefreshing];
        self.number += 20;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
}

- (void)getMusicData
{
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", self.docid];
    [AFNetTool getNetWithURL:str body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        self.listenArr = [NSMutableArray array];
        NSDictionary *dic = [responseObject objectForKey:self.docid];
        NSMutableArray *arr = [dic objectForKey:@"video"];
        self.listenArr = [MusicModel baseModelWithArr:arr];
        if (0 == self.listenArr.count) {
        } else {
            [self playAction];
            [self.imageV1 sd_setImageWithURL:(NSURL *)[[self.listenArr objectAtIndex:0] cover] placeholderImage:[UIImage imageNamed:@"音乐"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
}

- (NSString *)changeTimer:(CGFloat)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"mm:ss"];
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}

- (NSString *)changeEndTimer:(CGFloat)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"mm:ss"];
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
